package com.haojin.exer;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author .29.
 * @create 2022-03-31 15:37
 */
/*
    银行有一个账户
    有两个储户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额
 */



class Account1 implements Runnable {
    private static double balance = 0.0;
    ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            try {
                lock.lock();

                try{
                    Thread.sleep(100);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }

                balance += 1000.0;
                System.out.println(Thread.currentThread().getName() + "向账户存1000元，余额为：" + balance);

            } finally {
                lock.unlock();
            }
        }
    }
}

public class BankTest {
    public static void main(String[] args) {
        Account1 a = new Account1();
        Thread account1 = new Thread(a);
        Thread account2 = new Thread(a);

        account1.setName("储户1");
        account2.setName("储户2");

        account1.start();
        account2.start();

    }
}
